const cloud = require('@alipay/faas-server-sdk');
const COLLECTION = 'mall_order_info';
const COLLECTIONV2 = 'mall_order_detail';
exports.main = async (event, context) => {
    const db = cloud.database();
    // 查询 collection 中的 doc 列表，默认返回 100 条
    const data = {}
    if(event.status!=null){
      data.status = event.status;
    }
    if(event.userId!=null){
      data.userId = event.userId;
    }
    const docList = await db.collection(COLLECTION).where(data).get();
    console.log('当前 collection 中的 doc 列表:', docList);
    const orderist = docList.map(item => {
      return {
        id:item._id,
        time: item.gmtCreate,
        state: item.status,
        sum: item.totalAmount,
        total: item.totalCount
      };
    });
    for (const doc of orderist) {
      const orderDetailResp = await db.collection(COLLECTIONV2)
      .where({
        orderId: doc.id,
      }).get();
      console.log('orderDetailResp 列表:', orderDetailResp);
      const detailList = orderDetailResp.map(item => {
        return {
          title: item.title,
          description: item.description,
          price: item.price,
          num: item.count,
          image: item.image
        };
      });
      doc.commodity = detailList;
    }
  return orderist;
};